<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时追踪演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .header {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        .controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .controls button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        .btn-warning {
            background-color: #ffc107;
            color: black;
        }
        .status {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 4px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f8f9fa;
            font-family: monospace;
            font-size: 12px;
        }
        .message {
            margin-bottom: 5px;
            padding: 5px;
            border-radius: 3px;
        }
        .message.info {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
        }
        .message.warning {
            background-color: #fff3cd;
            color: #856404;
        }
        .input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        .input-group input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .locations-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        .location-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            background-color: #f8f9fa;
        }
        .location-card h4 {
            margin: 0 0 10px 0;
            color: #333;
        }
        .location-info {
            font-size: 14px;
            line-height: 1.4;
        }
        .location-info strong {
            color: #007bff;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚚 实时追踪演示</h1>
            <p>客、货、装备信息管理、追踪、监控实验平台</p>
        </div>

        <div id="status" class="status disconnected">
            状态: 未连接
        </div>

        <div class="controls">
            <button id="connectBtn" class="btn-primary" onclick="connect()">连接</button>
            <button id="disconnectBtn" class="btn-danger" onclick="disconnect()" disabled>断开连接</button>
            <button class="btn-success" onclick="getRealtimeLocations()">获取实时位置</button>
            <button class="btn-warning" onclick="clearMessages()">清空消息</button>
        </div>

        <div class="input-group">
            <input type="text" id="deviceIdInput" placeholder="设备ID (用于订阅)">
            <button class="btn-primary" onclick="subscribeDevice()">订阅设备</button>
            <button class="btn-warning" onclick="unsubscribeDevice()">取消订阅</button>
        </div>

        <div class="messages" id="messages"></div>

        <div id="locationsContainer" class="locations-grid"></div>
    </div>

    <script>
        let ws = null;
        let clientId = 'demo_' + Math.random().toString(36).substr(2, 9);

        function connect() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                addMessage('已经连接', 'warning');
                return;
            }

            const wsUrl = `ws://localhost:8000/ws/tracking/${clientId}`;
            ws = new WebSocket(wsUrl);

            ws.onopen = function(event) {
                updateStatus(true);
                addMessage('WebSocket连接已建立', 'success');
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
            };

            ws.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    handleMessage(data);
                } catch (e) {
                    addMessage('收到无效消息: ' + event.data, 'error');
                }
            };

            ws.onclose = function(event) {
                updateStatus(false);
                addMessage('WebSocket连接已关闭', 'warning');
                document.getElementById('connectBtn').disabled = false;
                document.getElementById('disconnectBtn').disabled = true;
            };

            ws.onerror = function(error) {
                addMessage('WebSocket错误: ' + error, 'error');
            };
        }

        function disconnect() {
            if (ws) {
                ws.close();
            }
        }

        function updateStatus(connected) {
            const statusEl = document.getElementById('status');
            if (connected) {
                statusEl.textContent = '状态: 已连接 (客户端ID: ' + clientId + ')';
                statusEl.className = 'status connected';
            } else {
                statusEl.textContent = '状态: 未连接';
                statusEl.className = 'status disconnected';
            }
        }

        function addMessage(message, type = 'info') {
            const messagesEl = document.getElementById('messages');
            const messageEl = document.createElement('div');
            messageEl.className = 'message ' + type;
            messageEl.textContent = new Date().toLocaleTimeString() + ' - ' + message;
            messagesEl.appendChild(messageEl);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }

        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
        }

        function subscribeDevice() {
            const deviceId = document.getElementById('deviceIdInput').value.trim();
            if (!deviceId) {
                addMessage('请输入设备ID', 'warning');
                return;
            }

            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addMessage('请先连接WebSocket', 'error');
                return;
            }

            const message = {
                type: 'subscribe_device',
                device_id: deviceId
            };

            ws.send(JSON.stringify(message));
            addMessage('发送订阅请求: ' + deviceId, 'info');
        }

        function unsubscribeDevice() {
            const deviceId = document.getElementById('deviceIdInput').value.trim();
            if (!deviceId) {
                addMessage('请输入设备ID', 'warning');
                return;
            }

            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addMessage('请先连接WebSocket', 'error');
                return;
            }

            const message = {
                type: 'unsubscribe_device',
                device_id: deviceId
            };

            ws.send(JSON.stringify(message));
            addMessage('发送取消订阅请求: ' + deviceId, 'info');
        }

        function getRealtimeLocations() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addMessage('请先连接WebSocket', 'error');
                return;
            }

            const message = {
                type: 'get_realtime_locations'
            };

            ws.send(JSON.stringify(message));
            addMessage('请求实时位置数据', 'info');
        }

        function handleMessage(data) {
            switch (data.type) {
                case 'subscription_confirmed':
                    addMessage('订阅确认: ' + data.message, 'success');
                    break;
                case 'unsubscription_confirmed':
                    addMessage('取消订阅确认: ' + data.message, 'success');
                    break;
                case 'realtime_locations':
                    addMessage('收到实时位置数据: ' + data.data.length + ' 个设备', 'success');
                    displayLocations(data.data);
                    break;
                case 'location_update':
                    addMessage('设备位置更新: ' + data.device_id, 'info');
                    break;
                case 'geofence_event':
                    addMessage('地理围栏事件: ' + JSON.stringify(data.data), 'warning');
                    break;
                case 'device_status_change':
                    addMessage('设备状态变化: ' + data.device_id + ' -> ' + data.status, 'info');
                    break;
                case 'periodic_location_update':
                    addMessage('定期位置更新: ' + data.data.length + ' 个设备', 'info');
                    displayLocations(data.data);
                    break;
                case 'pong':
                    addMessage('心跳响应', 'info');
                    break;
                case 'error':
                    addMessage('错误: ' + data.message, 'error');
                    break;
                default:
                    addMessage('未知消息类型: ' + data.type, 'warning');
            }
        }

        function displayLocations(locations) {
            const container = document.getElementById('locationsContainer');
            container.innerHTML = '';

            locations.forEach(location => {
                const card = document.createElement('div');
                card.className = 'location-card';
                
                card.innerHTML = `
                    <h4>📍 ${location.device_id}</h4>
                    <div class="location-info">
                        <strong>类型:</strong> ${location.device_type}<br>
                        <strong>位置:</strong> ${location.latitude}, ${location.longitude}<br>
                        <strong>地址:</strong> ${location.address || '未知'}<br>
                        <strong>速度:</strong> ${location.speed || 0} km/h<br>
                        <strong>电池:</strong> ${location.battery_level || 'N/A'}%<br>
                        <strong>信号:</strong> ${location.signal_strength || 'N/A'}%<br>
                        <strong>更新时间:</strong> ${new Date(location.last_update).toLocaleString()}
                        ${location.cargo_info ? `<br><strong>关联货物:</strong> ${location.cargo_info.name}` : ''}
                        ${location.equipment_info ? `<br><strong>关联装备:</strong> ${location.equipment_info.name}` : ''}
                    </div>
                `;
                
                container.appendChild(card);
            });
        }

        // 定期发送心跳
        setInterval(() => {
            if (ws && ws.readyState === WebSocket.OPEN) {
                const message = {
                    type: 'ping',
                    timestamp: Date.now()
                };
                ws.send(JSON.stringify(message));
            }
        }, 30000);

        // 页面加载时自动连接
        window.onload = function() {
            addMessage('页面加载完成，点击"连接"按钮开始', 'info');
        };
    </script>
</body>
</html>
